package com.config;

import java.io.Writer;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.page.PageMethod;
import com.server.user.AppUserBaseCtrl;
import com.server.user.UserCtrl;
import com.server.user.UserDAO;
import com.server.user.UserService;
import com.server.userCenter.UserCenterService;
import com.server.wx.WxUtil;
import com.util.IOUtil;
import com.util.StrKit;

/**
 * 用户过滤器
 * @author dell
 *
 */
public class AppUserInter implements HandlerInterceptor{
	
	@Autowired
	ConstService constService;
	@Autowired
	UserCtrl userCtrl;
	@Autowired
	UserDAO userDao;
	@Autowired
	WxUtil wxUtil;
	@Autowired
	UserService userService;
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception 
	{
		String url=request.getRequestURI();
		HttpSession session=request.getSession();
		String openid="";//用户Openid
		//本地测试使用
		if(ConstDefine.getIftest()==1)
		{
			if(session.getAttribute("openid")==null){
				session.setAttribute("openid", "okLFQ6VZQHAcu85Rhl9PfypuHh8I");
				Map<String, Object> user = userDao.getUserByOpenid("okLFQ6VZQHAcu85Rhl9PfypuHh8I");
				user.put("openid", "okLFQ6VZQHAcu85Rhl9PfypuHh8I");
				session.setAttribute("wxuser", user);
			}
		}
		
		boolean ifPassOpenid=false;//是否通过openid验证
		boolean ifPassLog=false;//是否通过用户登录验证
		
		//判断过滤注解
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            PassInter methodAnnotation =((HandlerMethod) handler).getMethodAnnotation(PassInter.class);
            if (methodAnnotation != null) {
            	ifPassOpenid=true;//是否通过openid验证
        		return true;
            }
        }
      //不经过openid的路径
		if(url.endsWith("/appUser/user/userReg")//注册
//				||url.contains("/appUser/shopOpen")//请求非登录链接
				||url.endsWith("/appUser/userCenter/aboutUs")//关于我们
				||url.endsWith("/appUser/userCenter/help")//帮助
				||url.contains("/pay/testPay")//请求非登录链接
				||url.contains("/pay/getTxPayRes")//微信支付回调
				||url.contains("/pay/getTxPayRes_front")//微信支付回调——前台地址
				||url.contains("/wxmsg")//公众号消息回调
				)
		{
			ifPassOpenid=true;
		}else{
			
			if(session.getAttribute("openid")!=null&&StrKit.notBlank((String)session.getAttribute("openid")))
			{
				System.out.println("wo have session");
				openid = (String) session.getAttribute("openid");
				
//				if(session.getAttribute("wxuser")==null)
//				{
//					Map<String, Object> user = userDao.getUserByOpenid(openid);//执行到这里一定有用户了
//					session.setAttribute("wxuser", user);
//				}
				
				ifPassOpenid=true;
			}else
			{
//				System.out.println("we do not hava session!");
				String code=request.getParameter("code");
//				System.out.println(urlsb.toString());
				if(StrKit.isBlank(code))
				{
					//重新跳转时，如果请求中包含商品ID，则封装到SESSION中
					if(request.getParameter("goodsid")!=null){
						session.setAttribute("goodsid", request.getParameter("goodsid"));
					}
					System.out.println("获取到code url::"+url);
					//重新封装URL
					StringBuffer urlsb=new StringBuffer(ConstDefine.getServerAddr()+url);
					System.out.println("urlsb:::"+urlsb.toString());
					String rdurl=URLEncoder.encode(urlsb.toString());
//					String rdurl=urlsb.toString();
//					String wxurl="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ConstDefine.appid+"&redirect_uri="+rdurl+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";//获取userinfo--需要用户同意
					String wxurl="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ConstDefine.getTxAppid()+"&redirect_uri="+rdurl+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";//获取openid--不需要用户同意
					
					response.sendRedirect(wxurl);
					return false;
				}else
				{
//					Map<String, String> map=wxUtil.getOpenidByCode(code);//只获取openid
					Map<String, String> map=wxUtil.getWXInfoByCode(code);//获取全部用户信息：不需要关注公众号
					openid=map.get("openid");
					
					//查询用户信息，需要关注才能获取头像名称等，可以判断是否关注了公众号，没关注直接跳转到关注
//					JSONObject userData = wxUtil.getUserInfoByOpenid(openid);
//					System.out.println("userinfo:"+userData.toString());
//					if(userData==null||userData.getInt("subscribe")==0)
//					{
//						response.sendRedirect("https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg5MTY5NDM3NA==&scene=124#wechat_redirect");
//						return false;
//					}
					//判断用户是否注册,没有就自动注册
//					userService.createUser(openid, map.get("nickname"), map.get("headimgurl"));
//					Map<String, Object> user = userDao.getUserByOpenid(openid);//执行到这里一定有用户了
//					session.setAttribute("wxuser", user);
					
					session.setAttribute("openid", openid);
					ifPassOpenid=true;
				}
			}
			  
		}

		//根据该IPENID判断是否注册
		if(ifPassOpenid&&!ifPassLog)
		{
			//不需要登录的链接
			if(url.endsWith("/pay/getWxPaySign_test")
					||url.endsWith("/appUser/user/goLog")//登陆
					||url.endsWith("/pay/goPayTest")
					||url.endsWith("/appUser/user/userReg")//注册
					||url.endsWith("/appUser/user/login")//登陆
//					||url.contains("/appUser/shopOpen")//请求非登录链接
					||url.endsWith("/appUser/userCenter/aboutUs")//关于我们
					||url.endsWith("/appUser/userCenter/help")//帮助
					||url.contains("/pay/testPay")//请求非登录链接
					||url.contains("/pay/getTxPayRes")//微信支付回调
					||url.contains("/pay/getTxPayRes_front")//微信支付回调——前台地址
					||url.contains("/wxmsg")//公众号消息回调
					)//测试支付使用
			{
				ifPassLog = true;
			}else{
				if(session.getAttribute("wxuser")!=null)
				{
					ifPassLog = true;
				}else{
					//根据openid查询用户
					System.out.println("根据Openid查询用户："+openid);
					Map<String, Object> user = userDao.getUserByOpenid(openid);
					if(user!=null){
						user.put("openid", openid);
						session.setAttribute("wxuser", user);
						ifPassLog = true;
					}else{//没有注册
						System.out.println("跳转到注册");
						response.sendRedirect(request.getContextPath()+"/appUser/user/goLog");
						return false;
					}
					
				}
			}
			
			
		}
		
		
		//判断分页,2个值都穿，默认为分页
		if(request.getParameter("pageNumber")!=null&&request.getParameter("pageSize")!=null)
		{
			PageMethod.startPage(Integer.parseInt(request.getParameter("pageNumber")),Integer.parseInt(request.getParameter("pageSize")));
		}		
		return ifPassOpenid;
	}

	
}
